package org.compiere.process;

import java.io.File;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Properties;

import org.adempiere.exceptions.AdempiereException;
import org.compiere.model.MAttachmentEntry;
import org.compiere.model.MBPartnerLocation;
import org.compiere.model.MLocation;
import org.compiere.model.Mhrmidcard;
import org.compiere.model.X_C_BPartner;
import org.compiere.model.X_hrm_idcard;
import org.compiere.util.Env;
import org.compiere.util.Language;
import org.compiere.util.Msg;
import org.eevolution.model.X_HR_Contract;
import org.joda.time.DateTime;

import extend.org.compiere.hrm.SearchReplace;
import extend.org.compiere.utils.Util;

/**
 * @author V.Sokolov
 * 
 * Class prepares file based on a contract.
 * The contract is formed on the pattern in which the right places prescribed parameters. 
 * In forming these parameters are replaced with the desired values​​.
 * 
 * Parameters:
 * {dtCurrent}			- Current date
 * {initial, employee}	- The initials of the employee
 * {jobdep}				- Position and department employee
 * {dtBegin}			- Beginning of the contract
 * {dtEnd}				- Termination of the contract
 * {periodTr}			- Trial period
 * {cardNum}			- Number identity card
 * {givenby}			- Issued by identity card
 * {dtIssue}			- Date of issue
 * {sic}				- Social individual code
 * {tin}				- Taxpayer identification number
 * {pin}				- Personal identification number
 * {phone}				- Phone number
 * {city}				- City of residence staff
 * {street}				- Street
 * {house}				- House number
 * Registered address
 * {regC}				- Registered city of residence staff
 * {regS}				- Registered street
 * {regH}				- Registered house number
 */
public class ContractPrint extends SvrProcess {
	
	/** Current context					*/
	private Properties m_ctx;
	/**	 */
	private ProcessInfo pi;
	/** */
	private X_HR_Contract contract = null;
	private String contractFile = "";
	/** */
	private String localFilePath = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator");
	/** */
	DateTime dtS;
	DateTime dtE;
	DateTime currentDate = new DateTime();

	@Override
	protected void prepare() {
		
		log.info("");
		m_ctx = Env.getCtx();
		pi = getProcessInfo();

		contract = new X_HR_Contract(getCtx(), getRecord_ID(), get_TrxName());
		dtS = new DateTime(contract.getValidFrom().getTime());
		if(contract.getValidTo() != null)
			dtE = new DateTime(contract.getValidTo().getTime());
		
		if(contract == null) return;
		
		// Labor Contract
		if(contract.gethrm_contractType().equals(X_HR_Contract.HRM_CONTRACTTYPE_Labor)){
			contractFile = "LaborContract";
		}

	}

	@Override
	protected String doIt() throws Exception {
		
		//
		MAttachmentEntry entry = Util.getAttachment(pi, m_ctx, contractFile);
		if(entry == null)
			throw new AdempiereException(Msg.translate(m_ctx, "NotFoundTemplate")+" "+contractFile);
		
		File inputFile = Util.getAttachmentEntryFile(entry);
		// We define a path to generate
		String fileExtension = entry.getName().substring(entry.getName().lastIndexOf("."),entry.getName().length());
		StringBuffer fullPath = new StringBuffer(localFilePath); 
		fullPath.append("Temp_").append(contractFile).append(fileExtension); 
		
		HashMap<String, String> searchTerms = new HashMap<String, String>();
		X_C_BPartner bp = new X_C_BPartner(m_ctx, contract.getC_BPartner_ID(), get_TrxName());
		MBPartnerLocation[] us = MBPartnerLocation.getForBPartner(m_ctx, contract.getC_BPartner_ID(), get_TrxName());
		int Location_ID = 0;
		int Registered_ID = 0;
		if(us.length != 0){
			Location_ID = us[0].getC_Location_ID();
			Registered_ID = us[0].getC_Registered_ID();
		}
		MLocation locat = new MLocation(m_ctx, Location_ID, get_TrxName());
		MLocation regLocat = new MLocation(m_ctx, Registered_ID, get_TrxName());
		Mhrmidcard card = Mhrmidcard.getHRM_Card(contract.getC_BPartner_ID(), X_hrm_idcard.HRM_DOCTYPE_Card, true);
		Mhrmidcard sic = Mhrmidcard.getHRM_Card(contract.getC_BPartner_ID(), X_hrm_idcard.HRM_DOCTYPE_Sic, true);
		
		// Set the default settings
		searchTerms.put("initial", "______________________________");
		searchTerms.put("jobdep", "______________________________.");
		searchTerms.put("dtEnd", "?");
		searchTerms.put("periodTr", "________");
		searchTerms.put("cardNum", "___________________");
		searchTerms.put("givenby", "____________");
		searchTerms.put("dtIssue", "?");
		searchTerms.put("sic", "___________________");
		searchTerms.put("tin", "___________________");
		searchTerms.put("pin", "___________________");
		searchTerms.put("phone", "___________________");		
		searchTerms.put("city", "");
		searchTerms.put("street", "");
		searchTerms.put("house", "");
		// Registered
		searchTerms.put("regC", "____________");
		searchTerms.put("regS", "____________");
		searchTerms.put("regH", "____________");
		
		// Current Date
		searchTerms.put("dtCurrent", "«"+Integer.toString(currentDate.getDayOfMonth())+"»"+" "+Util.getMonthName(new Timestamp(currentDate.getMillis()), Language.AD_Language_ru_RU, true)+" "+Integer.toString(currentDate.getYear()));
		// The initials of the employee
		if(bp.getLastName() != null && bp.getFirstName() != null){
			searchTerms.put("initial", bp.getLastName()+" "+bp.getFirstName()+" "+bp.getMiddleName());
			// Employee
			searchTerms.put("employee", bp.getLastName()+" "+bp.getFirstName()+" "+bp.getMiddleName());
		}
		else if(bp.getName() != null){
			searchTerms.put("initial", bp.getName());
			// Employee
			searchTerms.put("employee", bp.getName());
		}
		
		// Position and department employee
		if(contract.getHR_Job().getName() == null && contract.getHR_Department().getName() != null)
			searchTerms.put("jobdep", " ______________________________ "+contract.getHR_Department().getName()+".");
		else if(contract.getHR_Department().getName() == null && contract.getHR_Job().getName() != null)
			searchTerms.put("jobdep", contract.getHR_Job().getName()+" ______________________________.");
		else if(contract.getHR_Job().getName() != null && contract.getHR_Department().getName() != null)
			searchTerms.put("jobdep", contract.getHR_Job().getName()+" "+contract.getHR_Department().getName()+".");
		
		// Date begin
		searchTerms.put("dtBegin", "«"+Integer.toString(dtS.getDayOfMonth())+"»"+" "+Util.getMonthName(contract.getValidFrom(), Language.AD_Language_ru_RU, true)+" "+Integer.toString(dtS.getYear()));
		// Date end
		if(dtE != null)
			searchTerms.put("dtEnd", "«"+Integer.toString(dtE.getDayOfMonth())+"»"+" "+Util.getMonthName(contract.getValidTo(), Language.AD_Language_ru_RU, true)+" "+Integer.toString(dtE.getYear()));
		
		// Trial Period
		if(contract.gethrm_trialperiod().getName() != null)
			searchTerms.put("periodTr", contract.gethrm_trialperiod().getName());
		
		// Card Employee
		if(card.gethrm_valuedoc() != null)
			searchTerms.put("cardNum", card.gethrm_valuedoc());
		if(card.gethrm_givenby() != null)
			searchTerms.put("givenby", card.gethrm_givenby());
		if(card.gethrm_dateofissue() != null)
			searchTerms.put("dtIssue", "«"+Integer.toString(new DateTime(card.gethrm_dateofissue().getTime()).getDayOfMonth())+"»"+" "+Util.getMonthName(card.gethrm_dateofissue(), Language.AD_Language_ru_RU, true)+" "+Integer.toString(new DateTime(card.gethrm_dateofissue().getTime()).getYear()));
		if(sic.gethrm_valuedoc() != null)
			searchTerms.put("sic", sic.gethrm_valuedoc());			

		// taxpayer identification number
		if(bp.getFI_TIN() != null)
			searchTerms.put("tin", bp.getFI_TIN());
		// personal identification number
		if(bp.getFI_BIN_IIN() != null)
			searchTerms.put("pin", bp.getFI_BIN_IIN());
		// Phone employee
		if(us.length != 0 && us[0].getPhone() != null)
			searchTerms.put("phone", us[0].getPhone());			

		// Address Employee
		if(locat.getCity() != null){
			if(locat.getCity().startsWith("г"))
				searchTerms.put("city", locat.getCity());
			else
				searchTerms.put("city", "г. "+locat.getCity());
		}
		if(locat.getAddress2() != null){
			if(locat.getAddress2().startsWith("ул"))
				searchTerms.put("street", locat.getAddress2());
			else
				searchTerms.put("street", "ул. "+locat.getAddress2());
		}
		if(locat.getAddress3() != null){
			if(locat.getAddress3().startsWith("д"))
				searchTerms.put("house", locat.getAddress3());
			else
				searchTerms.put("house", "д. "+locat.getAddress3());
		}
		// Registered Address Employee
		if(regLocat.getCity() != null){
			if(regLocat.getCity().startsWith("г"))
				searchTerms.put("regC", regLocat.getCity());
			else
				searchTerms.put("regC", "г. "+regLocat.getCity());
		}
		if(regLocat.getAddress2() != null){
			if(regLocat.getAddress2().startsWith("ул"))
				searchTerms.put("regS", regLocat.getAddress2());
			else
				searchTerms.put("regS", "ул. "+regLocat.getAddress2());
		}
		if(regLocat.getAddress3() != null){
			if(regLocat.getAddress3().startsWith("д"))
				searchTerms.put("regH", regLocat.getAddress3());
			else
				searchTerms.put("regH", "д. "+regLocat.getAddress3());
		}
		
		// Substitute the data in the template settings
		SearchReplace searchReplace = new SearchReplace();
		searchReplace.searchAndReplace(inputFile, fullPath.toString(), searchTerms);
		
		// Open the file with the application associated
		String fileName = fullPath.toString();
		Util.launchFile(new File(fileName));
		
		return null;
	}
	
}
